<template>
  <div class="admin-page admin-score">
    <!-- 页面头部 -->
    <ScorePageHeader @score-entry="navigateToScoreEntry" />
    
    <el-card class="table-card">
      <!-- 过滤器 -->
      <ScoreFilter
        v-model="filters"
        :terms="terms"
        :courses="courses"
        :teaching-missions="teachingMissions"
        @search="searchScores"
        @reset="resetFilters"
        @term-change="handleTermChange"
        @course-change="handleCourseChange"
      />
      
      <!-- 成绩表格 - 直接显示，移除标签页结构 -->
      <div class="score-table-container">
        <el-table
          v-loading="loading"
          :data="paginatedStudentScores"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column label="序号" type="index" width="80" align="center" />
          <el-table-column label="学号" prop="studentNumber" min-width="120" resizable />
          <el-table-column label="姓名" prop="studentName" min-width="100" resizable />
          <el-table-column label="队次" prop="className" min-width="120" resizable />
          
          <!-- 动态生成的考核项列 -->
          <el-table-column
            v-for="part in examParts"
            :key="part.id"
            :label="`${part.name}(${part.proportion}%)`"
            min-width="100"
            resizable
          >
            <template #default="scope">
              <span :class="getScoreClass(scope.row.partScores[Number(part.id)])">
                {{ scope.row.partScores[Number(part.id)] ?? '-' }}
              </span>
            </template>
          </el-table-column>
          
          <!-- 最终成绩列 -->
          <el-table-column label="最终成绩" width="100" resizable>
            <template #default="scope">
              <span :class="getScoreClass(scope.row.finalScore)">
                {{ scope.row.finalScore ?? '-' }}
              </span>
            </template>
          </el-table-column>
          
          <!-- 操作列 -->
          <el-table-column label="操作" fixed="right" width="120" resizable>
            <template #default="scope">
              <el-button size="small" type="primary" @click="editStudentScore(scope.row)">
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <ScorePagination
        :total="totalScores"
        :page-size="pageSize"
        :current-page="currentPage"
        @page-change="handlePageChange"
      />
    </el-card>
    
    <!-- 成绩编辑对话框 -->
    <ScoreEditDialog
      v-model:visible="editDialogVisible"
      :type="editDialogType"
      :selected-score="selectedScore"
      :score-types="scoreTypes"
      @submit="handleScoreUpdate"
    />
    
    <!-- 教学任务选择对话框 -->
    <el-dialog
      v-model="showMissionSelectDialog"
      title="选择教学任务进行成绩录入"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="mission-select-content">
        <p class="dialog-tip">请选择一个教学任务进行成绩录入：</p>
        
        <!-- 教学任务过滤器 -->
        <el-form :inline="true" class="mission-filter-form">
          <el-form-item label="学期:">
            <el-select 
              v-model="missionSelectFilters.termId" 
              placeholder="选择学期"
              clearable
              style="width: 200px;"
              @change="handleMissionSelectTermChange"
            >
              <el-option
                v-for="term in terms"
                :key="term.id"
                :label="term.name"
                :value="term.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="课程:">
            <el-select 
              v-model="missionSelectFilters.courseId" 
              placeholder="选择课程"
              clearable
              style="width: 250px;"
              @change="filterMissions"
            >
              <el-option
                v-for="course in filteredCoursesForMissionSelect"
                :key="course.id"
                :label="course.name"
                :value="course.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        
        <!-- 教学任务列表 -->
        <el-table
          :data="filteredMissionsForSelect"
          highlight-current-row
          @current-change="handleMissionSelect"
          max-height="300"
          style="margin-top: 10px;"
        >
          <el-table-column prop="courseName" label="课程" width="150" />
          <el-table-column prop="termName" label="学期" width="100" />
          <el-table-column label="专业" width="120">
            <template #default="scope">
              <span v-if="scope.row.majorNames">{{ scope.row.majorNames.join(', ') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="授课教师" min-width="150">
            <template #default="scope">
              <span v-if="scope.row.teacherNames">{{ scope.row.teacherNames.join(', ') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学员人数" width="80">
            <template #default="scope">
              <el-tag size="small">{{ scope.row.studentCount || 0 }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMissionSelectDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="goToScoreEntry"
            :disabled="!selectedMissionForEntry"
          >
            进入成绩录入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'

// 导入组件
import ScorePageHeader from '@/components/base/forms/ScorePageHeader.vue'
import ScoreFilter from '@/components/base/filters/ScoreFilter.vue'
import ScorePagination from '@/components/base/tables/ScorePagination.vue'
import ScoreEditDialog from '@/components/score/dialogs/ScoreEditDialog.vue'

// 导入API
import { scoreApi } from '@/api/score'
import { teachingMissionApi } from '@/api/teaching-mission'
import { termApi, classApi } from '@/api/base-data'
import { scoreTypeApi } from '@/api/score-type'
import { courseExamPartApi } from '@/api/course-exam-part'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 成绩数据
const finalScores = ref([])
const partScores = ref([])
const examParts = ref([])
const studentScores = ref([])

// 基础数据
const teachingMissions = ref([])
const terms = ref([])
const courses = ref([])
const classes = ref([])
const scoreTypes = ref([])

// 过滤条件
const filters = reactive({
  termId: '',
  courseId: '',
  teachingMissionId: ''
})

// 编辑对话框相关
const editDialogVisible = ref(false)
const editDialogType = ref('final')
const selectedScore = ref({})

// 教学任务选择对话框相关
const showMissionSelectDialog = ref(false)
const selectedMissionForEntry = ref(null)

// 教学任务选择过滤器
const missionSelectFilters = reactive({
  termId: '',
  courseId: ''
})

// 计算属性 - 用于教学任务选择对话框的课程过滤
const filteredCoursesForMissionSelect = computed(() => {
  if (!teachingMissions.value || teachingMissions.value.length === 0) return []
  
  let filteredMissions = teachingMissions.value
  
  // 根据选中的学期过滤教学任务
  if (missionSelectFilters.termId) {
    filteredMissions = filteredMissions.filter(mission => 
      String(mission.termId) === String(missionSelectFilters.termId)
    )
  }
  
  // 从过滤后的教学任务中提取课程
  return extractCoursesFromMissions(filteredMissions)
})

// 计算属性 - 过滤教学任务用于选择
const filteredMissionsForSelect = computed(() => {
  if (!teachingMissions.value || teachingMissions.value.length === 0) return []
  
  let filtered = teachingMissions.value
  
  if (missionSelectFilters.termId) {
    filtered = filtered.filter(mission => 
      String(mission.termId) === String(missionSelectFilters.termId)
    )
  }
  
  if (missionSelectFilters.courseId) {
    filtered = filtered.filter(mission => 
      String(mission.courseId) === String(missionSelectFilters.courseId)
    )
  }
  
  return filtered
})

const filteredFinalScores = computed(() => {
  return finalScores.value || []
})

const filteredPartScores = computed(() => {
  return partScores.value || []
})

// 计算属性 - 获取当前选中教学任务的名称
const currentTeachingMissionName = computed(() => {
  if (!filters.teachingMissionId || !teachingMissions.value.length) return ''
  
  const mission = teachingMissions.value.find(m => String(m.id) === String(filters.teachingMissionId))
  if (mission) {
    return `${mission.courseName} - ${mission.classNames ? mission.classNames.join(', ') : '未知班级'}`
  }
  return ''
})

const paginatedStudentScores = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return studentScores.value.slice(start, end)
})

const totalScores = computed(() => {
  return studentScores.value.length
})

// 辅助函数 - 从教学任务中提取课程
const extractCoursesFromMissions = (missions) => {
  if (!missions || missions.length === 0) return []
  
  const courseMap = new Map()
  missions.forEach(mission => {
    if (mission.courseId && mission.courseName) {
      courseMap.set(mission.courseId, {
        id: mission.courseId,
        name: mission.courseName,
        code: mission.courseCode || ''
      })
    }
  })
  return Array.from(courseMap.values())
}

// 方法
const loadBaseData = async () => {
  try {
    const [termsRes, classesRes, missionsRes, scoreTypesRes] = await Promise.all([
      termApi.getAllTerms(),
      classApi.getAllClasses(),
      teachingMissionApi.getAllTeachingMissionsList(),
      scoreTypeApi.getAllScoreTypes()
    ])
    
    // 处理不同的响应格式
    terms.value = Array.isArray(termsRes) ? termsRes : (termsRes.data || [])
    classes.value = Array.isArray(classesRes) ? classesRes : (classesRes.data || [])
    teachingMissions.value = Array.isArray(missionsRes) ? missionsRes : (missionsRes.data || [])
    scoreTypes.value = Array.isArray(scoreTypesRes) ? scoreTypesRes : (scoreTypesRes.data || [])
    
    // 提取课程信息：根据教学任务数据提取唯一课程
    const courseMap = new Map()
    teachingMissions.value.forEach(mission => {
      if (mission.courseId && mission.courseName) {
        courseMap.set(mission.courseId, {
          id: mission.courseId,
          name: mission.courseName,
          code: mission.courseCode || ''
        })
      }
    })
    courses.value = Array.from(courseMap.values())
    
    // 设置当前学期为默认值
    const currentTermData = terms.value.find(term => term.isCurrent)
    if (currentTermData) {
      filters.termId = currentTermData.id
      // 同时设置教学任务选择对话框的学期为当前学期
      missionSelectFilters.termId = currentTermData.id
    }
    
  } catch (error) {
    console.error('加载基础数据失败:', error)
    ElMessage.error('加载基础数据失败')
  }
}

const loadScores = async () => {
  if (!filters.teachingMissionId) {
    finalScores.value = []
    partScores.value = []
    examParts.value = []
    studentScores.value = []
    return
  }
  
  loading.value = true
  try {
    // 使用教学任务ID获取成绩数据
    const [finalRes, partRes, examPartsRes] = await Promise.all([
      scoreApi.getFinalScoresByTeachingMission(filters.teachingMissionId),
      scoreApi.getPartScoresByTeachingMission(filters.teachingMissionId),
      courseExamPartApi.getExamPartsByTeachingMission(filters.teachingMissionId)
    ])
    
    let finalData = Array.isArray(finalRes) ? finalRes : (finalRes.data || [])
    let partData = Array.isArray(partRes) ? partRes : (partRes.data || [])
    let examPartsData = Array.isArray(examPartsRes) ? examPartsRes : (examPartsRes.data || [])
    
    finalScores.value = finalData
    partScores.value = partData
    examParts.value = examPartsData
    
    // 转换数据格式，按学生聚合成绩
    processStudentScores()
  } catch (error) {
    console.error('加载成绩数据失败:', error)
    ElMessage.error('加载成绩数据失败')
  } finally {
    loading.value = false
  }
}

const searchScores = (searchFilters) => {
  // 确保筛选条件正确同步到filters对象
  if (searchFilters) {
    Object.assign(filters, searchFilters)
  }
  
  currentPage.value = 1
  loadScores()
}

const resetFilters = async () => {
  Object.assign(filters, {
    termId: '',
    courseId: '',
    teachingMissionId: ''
  })
  currentPage.value = 1
  finalScores.value = []
  partScores.value = []
  
  // 重置后重新加载基础数据
  await loadBaseData()
}

const handleTermChange = async (termId) => {
  filters.courseId = ''
  filters.teachingMissionId = ''
  currentPage.value = 1
  finalScores.value = []
  partScores.value = []
  
  if (termId) {
    try {
      // 重新获取该学期对应的教学任务数据
      const missionsRes = await teachingMissionApi.getTeachingMissionsByTerm(termId)
      teachingMissions.value = Array.isArray(missionsRes) ? missionsRes : (missionsRes.data || [])
      
      // 更新课程列表
      const courseMap = new Map()
      teachingMissions.value.forEach(mission => {
        if (mission.courseId && mission.courseName) {
          courseMap.set(mission.courseId, {
            id: mission.courseId,
            name: mission.courseName,
            code: mission.courseCode || ''
          })
        }
      })
      courses.value = Array.from(courseMap.values())
    } catch (error) {
      console.error('获取教学任务失败:', error)
      ElMessage.error('获取教学任务数据失败')
    }
  } else {
    teachingMissions.value = []
  }
}

const handleCourseChange = (courseId) => {
  filters.teachingMissionId = ''
  currentPage.value = 1
  finalScores.value = []
  partScores.value = []
  // 不需要立即加载数据，等用户选择教学任务后再加载
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const navigateToScoreEntry = () => {
  // 显示教学任务选择对话框
  showMissionSelectDialog.value = true
}

// 教学任务选择对话框相关方法
const handleMissionSelect = (mission) => {
  selectedMissionForEntry.value = mission
}

const filterMissions = () => {
  // 过滤方法已经通过计算属性实现
}

// 教学任务选择对话框学期变化处理
const handleMissionSelectTermChange = () => {
  // 清空课程选择
  missionSelectFilters.courseId = ''
  // 清空已选中的教学任务
  selectedMissionForEntry.value = null
}

const goToScoreEntry = () => {
  if (!selectedMissionForEntry.value) {
    ElMessage.warning('请选择一个教学任务')
    return
  }
  
  // 跳转到教师用的成绩管理页面，并传递教学任务ID
  router.push({
    path: '/teaching-mission/score',
    query: { missionId: selectedMissionForEntry.value.id }
  })
  
  // 关闭对话框
  showMissionSelectDialog.value = false
  selectedMissionForEntry.value = null
}

// 数据处理方法 - 将分项成绩转换为按学生聚合的格式
const processStudentScores = () => {
  if (!finalScores.value || finalScores.value.length === 0) {
    studentScores.value = []
    return
  }

  const studentMap = new Map()
  
  // 处理最终成绩
  finalScores.value.forEach(score => {
    const key = score.studentId
    if (!studentMap.has(key)) {
      studentMap.set(key, {
        studentId: score.studentId,
        studentNumber: score.studentNumber,
        studentName: score.studentName,
        className: score.className,
        finalScore: score.score,
        partScores: {}
      })
    } else {
      studentMap.get(key).finalScore = score.score
    }
  })
  
  // 处理分项成绩
  partScores.value.forEach(partScore => {
    const key = partScore.studentId
    if (studentMap.has(key)) {
      // 统一转换为数字类型 - 修正字段名为scoreComponentId
      const examPartId = Number(partScore.scoreComponentId)
      studentMap.get(key).partScores[examPartId] = partScore.score
    }
  })
  
  studentScores.value = Array.from(studentMap.values())
}

// 辅助函数 - 根据分数返回样式类
const getScoreClass = (score) => {
  if (score === null || score === undefined || score === '-') {
    return 'score-empty'
  }
  
  const numScore = Number(score)
  if (isNaN(numScore)) {
    return 'score-empty'
  }
  
  if (numScore >= 90) {
    return 'score-excellent'
  } else if (numScore >= 80) {
    return 'score-good'
  } else if (numScore >= 70) {
    return 'score-average'
  } else if (numScore >= 60) {
    return 'score-pass'
  } else {
    return 'score-fail'
  }
}

// 编辑学生成绩
const editStudentScore = (row) => {
  selectedScore.value = {
    studentId: row.studentId,
    studentNumber: row.studentNumber,
    studentName: row.studentName,
    className: row.className,
    finalScore: row.finalScore,
    partScores: { ...row.partScores },
    teachingMissionId: filters.teachingMissionId
  }
  editDialogType.value = 'final'
  editDialogVisible.value = true
}

// 处理成绩更新
const handleScoreUpdate = async (updatedScore) => {
  try {
    loading.value = true
    
    // 更新最终成绩
    if (updatedScore.finalScore !== undefined) {
      await scoreApi.updateFinalScore({
        studentId: updatedScore.studentId,
        teachingMissionId: filters.teachingMissionId,
        score: updatedScore.finalScore
      })
    }
    
    // 更新分项成绩
    if (updatedScore.partScores) {
      for (const [examPartId, score] of Object.entries(updatedScore.partScores)) {
        await scoreApi.updatePartScore({
          studentId: updatedScore.studentId,
          teachingMissionId: filters.teachingMissionId,
          examPartId: parseInt(examPartId),
          score: score
        })
      }
    }
    
    ElMessage.success('成绩更新成功')
    editDialogVisible.value = false
    
    // 重新加载数据
    await loadScores()
  } catch (error) {
    console.error('更新成绩失败:', error)
    ElMessage.error('更新成绩失败')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadBaseData()
})
</script>

<style scoped>
.admin-page {
  padding: 20px;
}

.table-card {
  margin-top: 20px;
}

.score-tabs {
  margin-top: 20px;
}

.score-tabs :deep(.el-tabs__content) {
  padding: 20px 0;
}

/* 教学任务选择对话框样式 */
.mission-select-content {
  padding: 10px 0;
}

.dialog-tip {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
}

.mission-filter-form {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.mission-filter-form .el-form-item {
  margin-bottom: 0;
}

.dialog-footer .el-button + .el-button {
  margin-left: 10px;
}
</style>
